package com.easyOrder.web.action2.order;

import com.easyOrder.core.comm.BaseAction;
import com.easyOrder.core.context.ApiMethodAttribute;
import com.easyOrder.core.exception.api.InvalidOprationException;
import com.easyOrder.dto.OrderByMaterialDTO;
import com.easyOrder.dto.RequisitionDTO;
import com.easyOrder.dto.RequisitionDetailDTO;
import com.easyOrder.model.Requisition;
import com.easyOrder.model.RequisitionDetail;
import com.easyOrder.service.enums.RequisitionDetailState;
import com.easyOrder.service.enums.RequisitionState;
import com.easyOrder.service.invoice.InvoiceService;
import com.easyOrder.service.requisition.RequisitionDetailService;
import com.easyOrder.service.requisition.RequisitionService;
import com.easyOrder.web.action.requisition.RequisitionAction;
import com.google.common.collect.Lists;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * Created by liutao on 2017/7/21.
 */
@RestController
@RequestMapping("/receiver")
@ApiMethodAttribute(nonSignatureValidation = false)
public class ReceiverAction extends BaseAction{

    private static final Logger logger = Logger.getLogger(RequisitionAction.class);

    @Autowired
    private RequisitionService requisitionService;

    @Autowired
    private RequisitionDetailService requisitionDetailService;

    @Autowired
    private RedisTemplate<String, Boolean> springRedisTemplate;

    @Autowired
    private InvoiceService invoiceService;


    /**
     * 通过门店查询订单
     * @param branchId
     * @return
     */
    @RequestMapping(value = "/findOrderByBranchId", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object findOrderByBranchId(@RequestParam Long branchId){
        List<Integer> states = Lists.newArrayList();
        states.add(RequisitionState.pay.getValue());
        states.add(RequisitionState.receiving.getValue());
        states.add(RequisitionState.receivingPart.getValue());
        states.add(RequisitionState.completed.getValue());
        List<RequisitionDTO> requisitionDTOS = requisitionService.findByBranchId(branchId, states);
        return wrapperJsonView(requisitionDTOS);
    }

    /**
     * 通过主单id查询明细单
     * @param requisitionId
     * @return
     */
    @RequestMapping(value = "/findOrderDetailByOrderId", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object findOrderDetailByOrderId(@RequestParam Long requisitionId){
        List<RequisitionDetailDTO> requisitionDetailDTOS = requisitionDetailService.getRequisitionDetailDTOS(requisitionId);
        return wrapperJsonView(requisitionDetailDTOS);
    }


    /**
     * 接单（整单）
     * @param requisitionId
     * @return
     */
    @RequestMapping(value = "/getReceiver", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object getReceiver(@RequestParam Long requisitionId){
        String key = "receiver_get_" + requisitionId;
        String key2 = "receiver_get_" + requisitionId+"_detail";
        logger.warn("key:" + key);
        if (springRedisTemplate.hasKey(key)) {
            throw new InvalidOprationException("已有人接此单");
        } else if(springRedisTemplate.hasKey(key2)){
            throw new InvalidOprationException("已有人接此明细单");
        }else {
            springRedisTemplate.opsForValue().set(key, Boolean.TRUE, TimeUnit.MINUTES.toSeconds(1)*10, TimeUnit.SECONDS);
        }
        Requisition requisition = requisitionService.findById(requisitionId);
        checkArgument(requisition != null&&requisition.getStatusId()==RequisitionState.pay.getValue(), "此订单不能一键接单");
        requisitionService.updateRequisitionState(requisitionId, RequisitionState.receiving.getValue(), RequisitionDetailState.receiving.getValue(),null);
        return wrapperJsonView(new Date());
    }

    /**
     * 接单（部分）
     * @param detailId
     * @param requisitionId
     * @return
     */
    @RequestMapping(value = "/getReceiverByDetail", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object getReceiverByDetail(@RequestParam Long detailId,@RequestParam Long requisitionId){
        String key = "receiver_get_" + requisitionId;
        logger.warn("key:" + key);
        if (springRedisTemplate.hasKey(key)) {
            throw new InvalidOprationException("已有人接此单");
        } else {
            springRedisTemplate.opsForValue().set(key+"_detail", Boolean.TRUE, TimeUnit.MINUTES.toSeconds(1)*10, TimeUnit.SECONDS);
        }

        String keyDetail = "receiver_detail_get_" + detailId;
        logger.warn("keyDetail:" + keyDetail);
        if (springRedisTemplate.hasKey(keyDetail)) {
            throw new InvalidOprationException("已有人接此明细单");
        } else {
            springRedisTemplate.opsForValue().set(keyDetail, Boolean.TRUE, TimeUnit.MINUTES.toSeconds(1)*10, TimeUnit.SECONDS);
        }

        RequisitionDetail requisitionDetail = requisitionDetailService.findById(detailId);
        checkArgument(requisitionDetail != null&&requisitionDetail.getStatusId()== RequisitionDetailState.pay.getValue(), "状态错误");

        requisitionService.getReceiverByDetail(requisitionId, detailId);

        return wrapperJsonView(new Date());
    }


    /**
     * 通过物料分组查询明细
     * @param branchId
     * @return
     */
    @RequestMapping(value = "/getDetailGroupByMaterial", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object getDetailGroupByMaterial(@RequestParam Long branchId){
        List<OrderByMaterialDTO> orderByMaterialDTOS = invoiceService.getDetailGroupByMaterial(branchId);
        return wrapperJsonView(orderByMaterialDTOS);
    }

    /**
     * 通过物料id查询明细
     * @param branchId
     * @param materialId
     * @return
     */
    @RequestMapping(value = "/getDetailByMaterialId/{materialId}", method = {RequestMethod.GET, RequestMethod.OPTIONS})
    public Object getDetailByMaterialId(@RequestParam Long branchId,@PathVariable Long materialId){
        List<RequisitionDetailDTO> requisitionDetailDTOS = invoiceService.getDetailByMaterialId(branchId, materialId);
        return wrapperJsonView(requisitionDetailDTOS);
    }






}
